package org.aynu.propertyservice.service.impl;

import org.aynu.propertyservice.common.PropertyResponse;
import org.aynu.propertyservice.domain.PropertyFeesPo;
import org.aynu.propertyservice.feign.UserServiceClient;
import org.aynu.propertyservice.mapper.PropertyFeesMapper;
import org.aynu.propertyservice.service.IPropertyFeesService;
import org.aynu.userservice.common.UserResponse;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 物业费用表 服务实现类
 * </p>
 *
 * @author 小粥
 * @since 2025-03-03
 */
@Service
public class PropertyFeesServiceImpl extends ServiceImpl<PropertyFeesMapper, PropertyFeesPo> implements IPropertyFeesService {

    @Autowired
    private UserServiceClient userServiceClient;

    /**
     * 查询居民物业费清单
     *
     * @param propertyFeesPo 包含 userId, periodStart, periodEnd 的物业费对象
     * @return {@link PropertyResponse }<{@link List }<{@link PropertyFeesPo }>>
     */
    @Override
    public PropertyResponse<List<PropertyFeesPo>> selectResident(PropertyFeesPo propertyFeesPo) {
        List<PropertyFeesPo> list = lambdaQuery()
                .eq(PropertyFeesPo::getUserId, propertyFeesPo.getUserId())
                .eq(PropertyFeesPo::getPeriodStart, propertyFeesPo.getPeriodStart())
                .eq(PropertyFeesPo::getPeriodEnd, propertyFeesPo.getPeriodEnd())
                .list();
        return PropertyResponse.success(list, "所有用户已存在该年份缴费记录");
    }

    /**
     * 为所有没有缴费记录的居民创建缴费订单（排除 admin 角色用户）
     *
     * @param propertyFeesPo 包含 periodStart, periodEnd, amount 等信息的物业费对象
     * @return 创建的记录数量
     */
    @Override
    public int createAll(PropertyFeesPo propertyFeesPo) {
        // 1. 验证输入参数
        if (propertyFeesPo.getPeriodStart() == null) {
            throw new IllegalArgumentException("必须提供周期开始年份(periodStart)");
        }
        if (propertyFeesPo.getPeriodEnd() == null) {
            throw new IllegalArgumentException("必须提供周期结束年份(periodEnd)");
        }
        if (propertyFeesPo.getAmount() == null) {
            throw new IllegalArgumentException("必须提供金额(amount)");
        }
        if (propertyFeesPo.getDueDate() == null) {
            throw new IllegalArgumentException("必须提供到期日(dueDate)");
        }

        Integer periodStart = propertyFeesPo.getPeriodStart();
        Integer periodEnd = propertyFeesPo.getPeriodEnd();
        BigDecimal amount = propertyFeesPo.getAmount();
        LocalDate dueDate = propertyFeesPo.getDueDate();

        // 2. 获取所有用户信息
        ResponseEntity<UserResponse<List<Map<String, Object>>>> userResponse = userServiceClient.selectAllUser();
        if (!userResponse.getStatusCode().is2xxSuccessful()) {
            throw new RuntimeException("获取用户列表失败");
        }

        List<Map<String, Object>> allUsers = userResponse.getBody().getData();
        // 提取用户ID列表
        List<Integer> allUserIds = allUsers.stream()
                .map(user -> ((Number) user.get("userId")).intValue())
                .collect(Collectors.toList());
        // 提取用户角色映射
        Map<Integer, String> userRoles = allUsers.stream()
                .collect(Collectors.toMap(
                        user -> ((Number) user.get("userId")).intValue(),
                        user -> (String) user.get("role")
                ));

        // 3. 查询指定周期已有的缴费记录
        List<PropertyFeesPo> existingFees = lambdaQuery()
                .eq(PropertyFeesPo::getPeriodStart, periodStart)
                .eq(PropertyFeesPo::getPeriodEnd, periodEnd)
                .in(PropertyFeesPo::getUserId, allUserIds)
                .list();

        Set<Integer> usersWithFees = existingFees.stream()
                .map(PropertyFeesPo::getUserId)
                .collect(Collectors.toSet());

        // 4. 如果所有非 admin 用户都有记录，直接返回0
        long nonAdminUserCount = allUserIds.stream()
                .filter(userId -> !"admin".equals(userRoles.get(userId)))
                .count();
        long nonAdminWithFeesCount = usersWithFees.stream()
                .filter(userId -> !"admin".equals(userRoles.get(userId)))
                .count();
        if (nonAdminWithFeesCount == nonAdminUserCount) {
            return 0;
        }

        // 5. 为没有缴费记录的非 admin 用户创建订单
        int createdCount = 0;
        Timestamp now = new Timestamp(System.currentTimeMillis());

        for (Integer userId : allUserIds) {
            // 跳过 admin 用户和已有缴费记录的用户
            if ("admin".equals(userRoles.get(userId)) || usersWithFees.contains(userId)) {
                continue;
            }

            PropertyFeesPo newFee = new PropertyFeesPo()
                    .setUserId(userId)
                    .setPeriodStart(periodStart)
                    .setPeriodEnd(periodEnd)
                    .setAmount(amount)
                    .setStatus("未支付")
                    .setDueDate(dueDate)
                    .setCreatedAt(now);

            save(newFee);
            createdCount++;
        }

        return createdCount;
    }
}